package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.benmanes.caffeine.cache.Cache;
import com.hmdp.constants.RedisConstants;
import com.hmdp.constants.SystemConstants;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.LockUtils;
import com.hmdp.utils.RedisCacheUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.hmdp.constants.SystemConstants.SHOP_NOT_EXIST;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zdq
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private LockUtils lockUtils;
    @Resource
    private RedisCacheUtils redisCacheUtils;
    @Resource
    private RedissonClient redissonClient;

    // @Resource
    private Cache<String, Object> cache;


    @Override
    public Result queryShopById(Long id) throws InterruptedException {
        Shop shop = redisCacheUtils.queryWithTTL(
                RedisConstants.CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                RedisConstants.CACHE_SHOP_TTL,
                TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result updateShop(Shop shop) {
        // 更新数据库
        if (shop == null || shop.getId() == null) {
            return Result.fail("商铺id不能为空，更新失败");
        }
        updateById(shop);

        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());

        return Result.ok();
    }

    @Override
    public Result queryShopOfType(Integer typeId, Integer current, Double x, Double y) {

        // x, y 为空直接查数据库
        if (x == null || y == null) {
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 分页参数
        int start = SystemConstants.DEFAULT_PAGE_SIZE * (current - 1);
        int end = start + SystemConstants.DEFAULT_PAGE_SIZE;


        // 查询 redis
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> search = stringRedisTemplate.opsForGeo()
                .search(
                        key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeCoordinates().limit(end)
                );

        // 解析id
        if (search == null) {
            return Result.ok(Collections.emptyList());
        }


        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> idList = search.getContent();
        if (start >= search.getContent().size()) {
            return Result.ok(Collections.emptyList());
        }

        ArrayList<Long> ids = new ArrayList<>(end - start + 1);
        HashMap<Long, Distance> map = new HashMap<>(end - start + 1);
        // 从 start 开始截取
        idList.stream().skip(start).forEach(item -> {
            Long id = Long.valueOf(item.getContent().getName());
            ids.add(id);
            Distance distance = item.getDistance();
            map.put(id, distance);
        });

        // 根据 ids 根据查询商户信息
        String join = StrUtil.join(",", ids);
        List<Shop> list = query().in("in", ids).last("ORDER BY FLIED(id," + join + ")").list();
        for (Shop shop: list) {
            shop.setDistance(map.get(shop.getId()).getValue());
        }
        return Result.ok(list);
    }

    @Override
    public Result getShopByTypeId(Integer typeId, Integer current, Double x, Double y) {
        String key = RedisConstants.CACHE_SHOP_LIST_KEY + typeId + ":" + current;

        /* 查询Caffeine
        List<Shop> typeList = (List<Shop>) cache.get(key, k -> null);
        if (typeList != null) {
            return Result.ok(typeList);
        } */

        // 查询缓存
        String shopListStr = stringRedisTemplate.opsForValue().get(key);
        List<Shop> typeList;
        if (StrUtil.isNotBlank(shopListStr)) {
            typeList = JSON.parseArray(shopListStr, Shop.class);
            // cache.put(key, typeList);
            return Result.ok(typeList);
        }

        // 获得锁的去查询数据库
        RLock lock = redissonClient.getLock(RedisConstants.LOCK_REDISSON_KEY + typeId + ":" + current);
        lock.lock();

        try {
            // 再次查询
            shopListStr = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(shopListStr)) {
                typeList = JSON.parseArray(shopListStr, Shop.class);
                return Result.ok(typeList);
            }

            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            typeList = page.getRecords();

            // 加入缓存
            stringRedisTemplate.opsForValue().set(key, JSON.toJSONString(typeList));
            // cache.put(key, typeList);

            // 返回数据
            return Result.ok(typeList);
        } finally {
            lock.unlock();
        }
    }
}
